# TODO: Add comment
# 
# Author: broken
###############################################################################
library(raster)
library(base)
library(gstat)

path= "/var/www/html/fimo/apom/Resample/SatResampMOD04/"
shap=shapefile("/home/phamha/BDNEN/VNM_adm0.shp")

a=c(2009,2010,2011,2012,2013,2014)
for (i in 1:6) {
	inputPath=paste(path,a[i],sep="")
	cout=array(0,9)
	listFile = list.files(path = inputPath,pattern="DT_10km.tif$",full.names = TRUE,recursive=TRUE)
	listSize=length(listFile)
	for(j in 1:listSize){
		
		
		#check file exist
		
		rasterFile=raster(listFile[j])
		
		#get total pixel in VN
		#raster2=rasterFile
		#rasterValues2=values(raster2)
		#total2=ncell(rasterValues2)
	
		#raster2[1:total2]=100
		#raster2=crop(raster2,shap)
		#raster2=mask(raster2,shap)
		#rasterValues2=values(raster2)
		#total_pixcel2=sum(!is.na(rasterValues2))
		
		#get valuable pixel in VN
		rasterFile=crop(rasterFile,shap)
		rasterFile=mask(rasterFile,shap)
		
		rasterValues=values(rasterFile)
		
		valid_pixcel=sum(!is.na(rasterValues))
		#total_pixcel=ncell(rasterValues1)
		
		ratio=valid_pixcel/2024*100
		
		if(ratio>=90){
			cout[9]=cout[9]+1
			cout[8]=cout[8]+1
			cout[7]=cout[7]+1
			cout[6]=cout[6]+1
			cout[5]=cout[5]+1
			cout[4]=cout[4]+1
			cout[3]=cout[3]+1
			cout[2]=cout[2]+1
			cout[1]=cout[1]+1
		}
		if(ratio>=80&&ratio<90){
			cout[8]=cout[8]+1
			cout[7]=cout[7]+1
			cout[6]=cout[6]+1
			cout[5]=cout[5]+1
			cout[4]=cout[4]+1
			cout[3]=cout[3]+1
			cout[2]=cout[2]+1
			cout[1]=cout[1]+1
		}
		if(ratio>=70&&ratio<80){
			
			cout[7]=cout[7]+1
			cout[6]=cout[6]+1
			cout[5]=cout[5]+1
			cout[4]=cout[4]+1
			cout[3]=cout[3]+1
			cout[2]=cout[2]+1
			cout[1]=cout[1]+1
		}
		if(ratio>=60&&ratio<70){
			cout[6]=cout[6]+1
			cout[5]=cout[5]+1
			cout[4]=cout[4]+1
			cout[3]=cout[3]+1
			cout[2]=cout[2]+1
			cout[1]=cout[1]+1
		}
		if(ratio>=50&&ratio<60){
			
			cout[5]=cout[5]+1
			cout[4]=cout[4]+1
			cout[3]=cout[3]+1
			cout[2]=cout[2]+1
			cout[1]=cout[1]+1
		}
		if(ratio>=40&&ratio<50){
			
			cout[4]=cout[4]+1
			cout[3]=cout[3]+1
			cout[2]=cout[2]+1
			cout[1]=cout[1]+1
		}
		if(ratio>=30&&ratio<40){
			cout[3]=cout[3]+1
			cout[2]=cout[2]+1
			cout[1]=cout[1]+1
		}
		if(ratio>=20&&ratio<30){
			
			cout[2]=cout[2]+1
			cout[1]=cout[1]+1
		}
		if(ratio>=10&&ratio<20){
			cout[1]=cout[1]+1
		}
		
	}
	print(paste(a[i],":",listSize,sep=""))
	print(cout)
}
